function [flag, vec] = newtoniter(func, x, v, tol)
%NEWTONITER - Newton iteration process for homotopy method.
%
% Inputs:
%   func - Here are some descriptions about the parameter func
%   x - Here are some descriptions about the parameter x0
%   v - Here are some descriptions about the parameter x0
%   tol - Here are some descriptions about the parameter tol
%
% Outputs:
%   flag - Here are some descriptions about the parameter flag
%   vec - Here are some descriptions about the parameter vec
%
    flag = 0;
    n = length(x);
    % 在 (v, tau) 平面上使用初值为 x0 的 Newton 迭代
    m = 1;  % number of Newton iteration
    z = [];
    z(:, m) = x;
    while true
        DF = [jacobian(func, z(:, m)); v'];
        v3 = func(z(:, m));
        F = [v3; v(1:n-1)' * (z(1:n-1, m) - z(1:n-1, 1)) + v(n) * (z(n, m) - z(n, 1))];
        % Newton iteration scheme
        z(:, m+1) = z(:, m) - inv(DF) * F;

        sigma = norm(z(:, m+1) - z(:, m));
        % 迭代停止判断
        if sigma <= tol
            flag = 1;
            vec = z(:, m+1);
            break;
        end
        if m >= 2
            sigma2 = norm(z(:, m) - z(:, m-1));
            if sigma > sigma2 / 3
                vec = [];
                break;
            end
            if sigma^2 <= tol * (sigma2 - sigma)
                flag = 1;
                vec = z(:, m+1);
                break;
            end
        end
        m = m + 1;
    end
end
